<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <div>
        <!-- <el-row class="form-info" v-if="route.query.mode !== 'add'">
          <el-col :span="7" :offset="1"
            >申请人: {{ infoState.createUserName }}</el-col
          >
          <el-col :span="7">创建时间: {{ infoState.createTime }}</el-col>
          <el-col :xl="8" :lg="12">文档编号: {{ infoState.billNum }}</el-col>
        </el-row> -->
        <el-form
          ref="formRef"
          @submit.prevent
          :model="formState"
          :rules="Rules"
          label-width="160px"
        >
          <el-form-item label="标题" placeholder="请输入标题" prop="title">
            <el-input
              :disabled="!isEdit"
              v-model="formState.title"
              class="width-custom220"
            />
          </el-form-item>
          <el-form-item
            label="所属项目"
            placeholder="请选择所属项目"
            prop="projectId"
          >
            <el-select
              v-model="formState.projectId"
              placeholder="请选择"
              :disabled="!isEdit"
              value-key="id"
              @change="handleSelected"
              class="width-custom220"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="项目阶段"
            placeholder="请选择项目阶段"
            prop="projectStage"
          >
            <el-select
              v-model="formState.projectStage"
              :disabled="!isEdit"
              class="width-custom220"
            >
              <el-option
                v-for="item in projectTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="参评人" prop="participant">
            <SelectForTable
              ref="selectTable"
              @change="changeParticipant"
              :value="formState.participantList"
              :disabled="!isEdit"
            />
          </el-form-item>
          <el-form-item label="会议时间" prop="occurrenceTime">
            <el-date-picker
              v-model="formState.occurrenceTime"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
            />
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item
                label="上传文档"
                placeholder="请上传文档"
                prop="attachmentArr"
              >
                <el-upload
                  v-if="isEdit"
                  name="uploadFile"
                  multiple
                  :accept="acceptTypes"
                  :action="uploadComUrl"
                  :headers="uploadHeaders"
                  :on-success="handleSuccess"
                  :on-remove="handleRemove"
                  :on-error="handleError"
                  :file-list="defaultFileList"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePreview"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                    </div>
                  </template>
                </el-upload>
                <template v-else>
                  <div
                    v-for="item in formState.attachmentArr"
                    :key="item?.uuidFile"
                  >
                    <el-link
                      icon="el-icon-folder"
                      @click.prevent="handleDownload(item)"
                    >
                      {{ item.fileName }}&emsp;
                    </el-link>
                    <br />
                  </div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="评审摘要" placeholder="请输入" prop="summary">
            <el-input
              type="textarea"
              autosize
              :disabled="!isEdit"
              v-model="formState.summary"
            ></el-input>
          </el-form-item>

          <el-form-item label="备注" placeholder="请输入" prop="remark">
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.remark"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import SelectForTable from "/@/components/selectForTable/index.vue";
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import * as api from "/@/api/meet";
import { postProjectList } from "/@/api/project";
import { postDictList } from "/@/api/common";
import { useUpload } from "/@/hooks";

const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders,
  onInitFileList
} = useUpload();
const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};
const handleDownload = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
  );
};
// const projectRef = ref<HTMLElement | null>(null) as any;
// const projectTreeRef = ref<HTMLElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;
const router = useRouter();
const route = useRoute();

let projectList = ref([]);
let selectTable = ref(null);

let projectTypeList = ref([]);
let copyProjectPhaseList = ref([]);

const formState = reactive({
  title: "",
  participant: [],
  // projectName: null,
  participantList: [],
  projectId: null,
  occurrenceTime: null,
  // contractName: null,
  // rdContractId: null,
  projectStage: "",
  summary: "",
  attachmentArr: [],
  remark: ""
});

const Rules = {
  title: [{ required: true, message: "请输入变更名称", trigger: "blur" }],
  projectId: [{ required: true, message: "请选择所属项目", trigger: "change" }],
  // rdContractId: [{ required: true, message: "请选择合同", trigger: "change" }],
  projectStage: [
    { required: true, message: "请选择项目阶段", trigger: "change" }
  ],
  // summary: [{ required: true, message: "请输入", trigger: "change" }],

  attachmentArr: [{ required: true, message: "请选择文件", trigger: "change" }],
  participant: [{ required: true, message: "请选择参评人", trigger: "change" }],
  occurrenceTime: [
    { required: true, message: "请选择会议时间", trigger: "change" }
  ]
};

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

const changeParticipant = item => {
  formState.participant = item;
};

// watch(
//   () => formState.projectId,
//   newVal => {
//     if (newVal) {
//       // formState.projectId = newVal.id;
//       getContractList();
//     }
//   },
//   {
//     deep: true
//   }
// );

// 上传 --start
let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formState.attachmentArr = formState.attachmentArr.filter(item => {
    const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
    return item.uuidFile !== uuid;
  });
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formState.attachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

/* 上传 -- end */

const goback = () => {
  router.push("/project/meet");
};

const getDetail = async () => {
  try {
    const params = {
      id: route.query.id
    };
    const { code, data } = await api.postMeetInfo(params);
    if (code === 200) {
      // console.log(code, data);
      const {
        // createTime,
        // createUserName,
        // billNum,
        title,
        projectName,
        projectId,
        // contractName,
        // rdContractId,
        projectStage,
        summary,
        attachmentArr,
        remark,
        occurrenceTime
      } = data;

      // infoState.createTime = createTime;
      // infoState.createUserName = createUserName;
      // infoState.billNum = billNum;

      formState.title = title;
      formState.occurrenceTime = occurrenceTime;
      // formState.projectName = projectName;
      // formState.contractName = contractName;
      // formState.rdContractId = rdContractId;
      formState.projectStage = projectStage;
      formState.summary = summary;
      formState.attachmentArr = attachmentArr;

      // ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      // TODO
      // formState.projectId = {
      //   id:projectId
      //   projectName:""
      // };

      formState.projectId = { id: projectId, projectName };
      // ------------------------------------------------------------------------------------------------------------------------------------------------------------------------

      // formState.attachmentArr = attachmentArr;
      defaultFileList.value = onInitFileList(attachmentArr);

      formState.remark = remark;
      // console.log(formState, "formState");

      const currentProject = projectList.value.find(item => {
        return item.id === +projectId;
      });

      const oldStage = JSON.parse(currentProject?.projectStage ?? '"[]"');
      const newStage = copyProjectPhaseList.value.filter(item => {
        if (oldStage.includes(item.dicCode)) {
          return item;
        }
      });
      projectTypeList.value = newStage;

      formState.participant = data.participantList.map(el => el.userId);
      formState.participantList = data.participantList;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSelected = val => {
  formState.projectStage = "";
  const oldStage = JSON.parse(val.projectStage);
  const newStage = copyProjectPhaseList.value.filter(item => {
    if (oldStage.includes(item.dicCode)) {
      return item;
    }
  });
  projectTypeList.value = newStage;
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

const handleSubmit = () => {
  // formState.attachmentArr = onFilterFileData(defaultFileList.value);
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const parList = selectTable.value.participantList;
      const copyFormData = JSON.parse(JSON.stringify(formState));
      copyFormData.projectId = formState.projectId.id;
      copyFormData.participant = JSON.stringify(copyFormData.participant);
      copyFormData.participantList = parList.map(el => {
        return { userId: el.id, userName: el.userName, name: el.name };
      });

      if (route.query.mode === "add") {
        const { code, message } = await api.postMeetAdd(copyFormData);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        copyFormData.id = route.query.id;
        const { code, message } = await api.postMeetUpdate(
          Object.assign(copyFormData, { id: route.query.id })
        );
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};

// const handleCheckChange = () => {
//   const res = projectTreeRef.value.getCurrentNode();
//   formState.projectName = [res][0].projectName;
//   formState.projectId = [res][0].id;
//   formState.rdContractId = "";
//   formState.contractName = "";
//   projectRef.value.blur();
// };

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取合同信息
// const getContractList = async () => {
//   try {
//     const params = {
//       projectId: formState.projectId,
//       pageNum: 1,
//       pageSize: 0
//     };
//     const { code, data } = await postContractList(params);
//     if (code === 200) {
//       contracList.value = data.list;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// const handleChangeContract = async () => {
// if (formState.rdContractId) {
//   const params = {
//     id: formState.rdContractId
//   };
//   const { code, data } = await getContractInfo(params);
//   if (code === 200 && data) {
//     const { projectId, projectName, contractName } = data;
//     formState.projectName = projectName;
//     formState.projectId = projectId;
//     formState.contractName = contractName;
//   }
// }
// };

const initprojectTypeList = async () => {
  try {
    const params = {
      dicType: "rd_project_stage"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectTypeList.value = data;
      copyProjectPhaseList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(async () => {
  await initprojectTypeList();
  await getProjectList();
  if (route.query.mode !== "add") {
    await getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.width-custom220 {
  width: 220px;
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}

// .el-select-dropdown__item {
//   height: auto;
//   // min-height: 100px;
//   // max-height: 274px;
//   padding: 0;
//   overflow-x: hidden;
//   overflow-y: hidden;
// }
// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// // .tree-option
// .tree-option :deep .el-tree-node__content {
//   height: auto;
//   padding: 0 10px;
// }
// // .tree-option :deep .el-select-dropdown__list {
// //   padding: 0 6px;
// // }
// .tree-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   margin-right: 10px;
// }

// .el-tree :deep .is-current .el-tree-node__label {
//   color: #409eff;
//   font-weight: 700;
// }
// .el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
//   color: #606266;
//   font-weight: normal;
// }
// .default-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   // margin-right: 10px;
// }

// .default-option {
//   padding: 0 10px;
// }
</style>
